package com.ny.service.impl;

import com.ny.entity.Devices;
import com.ny.repository.DevicesRepository;
import com.ny.service.DevicesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DevicesServiceImpl implements DevicesService {
    
    @Autowired
    private DevicesRepository devicesRepository;


    @Override
    public List<Devices> findAll() {
        return devicesRepository.findAll();
    }
    
    @Override
    public List<Devices> findByName(String name) {
        return devicesRepository.findByName(name);
    }
    
    @Override
    public List<Devices> findByNameContaining(String name) {
        return devicesRepository.findByNameContaining(name);
    }
    
    @Override
    public Devices addDevice(Devices device) {
        return devicesRepository.save(device);
    }
    
    @Override
    public Devices updateDevice(int deviceId, Devices device) {
        try {
            List<Devices> existingDevices = devicesRepository.findByDevice_id(deviceId);
            if (existingDevices != null && !existingDevices.isEmpty()) {
                // 使用第一个匹配的设备进行更新
                Devices existingDevice = existingDevices.get(0);
                // 更新设备信息
                existingDevice.setName(device.getName());
                existingDevice.setType(device.getType());
                existingDevice.setStatus(device.getStatus());
                existingDevice.setRoom(device.getRoom());
                existingDevice.setBrightness(device.getBrightness());
                existingDevice.setDevice_id(device.getDevice_id());
                // 可以根据需要更新其他字段
                return devicesRepository.save(existingDevice);
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException("更新设备时发生错误: " + e.getMessage(), e);
        }
    }
    
    @Override
    public void deleteDevice(int deviceId) {
        try {
            List<Devices> devices = devicesRepository.findByDevice_id(deviceId);
            if (devices != null && !devices.isEmpty()) {
                // 删除所有匹配的设备
                devicesRepository.deleteAll(devices);
            }
        } catch (Exception e) {
            throw new RuntimeException("删除设备时发生错误: " + e.getMessage(), e);
        }
    }
}